// 引入express框架
var express = require('express');
// 创建路由对象
var router = express.Router();
const jwt = require('jsonwebtoken');
const SECRET = 'your_secret_key'; // 建议放到环境变量
let userModel = require('../db/user');
// 登录接口
router.post('/login', async function(req, res) {
  const { username, password,jobNumber } = req.body;
  console.log(username,password,jobNumber);
  
  const user = await userModel.findOne({ name:username, password,jobNumber });
  if (!user) {
    return res.json({ code: 401, msg: '用户名或密码错误' });
  }
  // 生成accessToken和refreshToken
  const accessToken = jwt.sign({ jobNumber, type: 'access' }, SECRET, { expiresIn: '10m' });
  const refreshToken = jwt.sign({ jobNumber, type: 'refresh' }, SECRET, { expiresIn: '7d' });
  res.json({ code: 200, data:user,accessToken, refreshToken });
});

// token校验中间件示例
function verifyAccessToken(req, res, next) {
  const token = req.headers['authorization'];
  if (!token) return res.status(401).json({ msg: '无token' });
  jwt.verify(token, SECRET, (err, decoded) => {
    if (err) return res.status(401).json({ msg: 'token无效' });
    req.user = decoded;
    next();
  });
}
module.exports = router;
